/**
 * @Author: likang xie
 * @Date: 2019-11-13 14:15:57
 * @Usage: 上传图片/文件
 */

import config from "@/config";
import store from "@/store";
import toast from "@/utils/toast";

/**
 * @param path 文件链接
 */
export default path => {
  return new Promise((resolve, reject) => {
    let url = "/api/fileUpload";

    // #ifdef H5
    config.remote = "";
    // #endif

    // #ifndef H5
    url = url.replace("/doc", "");
    // #endif
    console.log("url", url);
    uni
      .uploadFile({
        url: config.remote + url,
        filePath: path,
        name: "file",
        formData: {
          token: uni.getStorageSync("userInfo").token || ""
        }
      })
      .then(chunk => {
        let [err, res] = chunk;

        if (res) {
          let { code, data, message } = JSON.parse(res.data);

          // 未登录/重新登录/Token过期
          if (code == 1011) {
            toast("未登录或已过期");
            store.dispatch("SET_USER_INFO", "");
            return uni.navigateTo({
              url: "/user/login"
            });
          }

          if (code != 1000) return toast(message || "上传失败，请重试");
          resolve(data);
        } else {
          console.error(err);
          reject(err);
        }
      });
  });
};
export let urlTobase64 = (url)=>{
  uni.request({
    url: url,
    method: 'GET',
    responseType: 'arraybuffer',
    success: res => {
        let base64 = wx.arrayBufferToBase64(res.data); //把arraybuffer转成base64
        base64 = 'data:image/jpeg;base64,' + base64; //不加上这串字符，在页面无法显示
        console.log(base64);
        return base64;
    }
});
}
/**
 * @method: app 本地文件上传
 * @param path 文件路径
 */
export const appUpload = path => {
	return new Promise((resolve, reject) => {
		let url = "/fileUpload";
		let userInfo = uni.getStorageSync("userInfo") || {};
		
		var uploadTask = plus.uploader.createUpload(config.remote + url, { method: "POST" }, (response, status) => {
			console.log(status);
			if (status === 200) {
				let { code, data, message } = JSON.parse(response.responseText);
				console.log(response);
				if (code === 1000) {
					resolve(data);
				} else reject("上传失败");
				
				// 未登录/重新登录/Token过期
				if (code == 1011) {
				  toast("未登录或已过期");
				  store.dispatch("SET_USER_INFO", "");
				  return uni.navigateTo({
				    url: "/user/login"
				  });
				}
			} else {
				reject("上传失败");
			}
		});
		uploadTask.addFile(path, { key: "file" });
		uploadTask.addData("token", userInfo.token);
		uploadTask.start();
	});
}
